package demo.demo10;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class test09 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchFieldException {
        //获取Class对象
        Class<?> aClass = Class.forName("demo.demo10.User01");

        //构造一个对象
        Object user = (User01) aClass.newInstance();
        System.out.println(user);

        //通过构造器创建对象
        Constructor<?> declaredConstructor = aClass.getDeclaredConstructor(String.class, int.class, int.class);
        User01 user1 = (User01) declaredConstructor.newInstance("zyh", 001, 18);
        System.out.println(user1);
        //    通过反射调用普通方法
        User01 user2 = (User01) aClass.newInstance();
        //通过反射获取一个方法
        Method setName = aClass.getDeclaredMethod("setName", String.class);
        //invoke  激活的意思
        //（对象。“方法的值”）
        setName.invoke(user2, "zyh");
        System.out.println(user2.getName());

        //通过反射获取操作属性
        User01 user3 = (User01) aClass.newInstance();
        Field name = aClass.getDeclaredField("name");

        //不能直接操作私有属性，我呢需要关掉程序的安全检测，
        name.setAccessible(true);//关闭安全检测
        name.set(user3, "zyh");
        System.out.println(user3.getName());
    }
}